<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>联系人列表</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <style>
        .contact-list-item {
            cursor: pointer;
        }

        .container {
            display: flex;
            justify-content: center;
            align-items: center;
        }

    </style>
</head>
<body>

<header th:include="index.html::top"></header>

<div class="container">

    <form>
        <h5>联系人列表</h5>

        <div class="input-group">
            <input type="text" class="form-control" id="searchInput" placeholder="搜索联系人">
            <div class="input-group-append">
                <button class="btn btn-primary" type="button" id="searchButton">搜索</button>
            </div>
        </div>


        <div class="btn-group" role="group">
            <button type="button" class="btn btn-primary" onclick="filterContacts('all')">全部</button>
            <button type="button" class="btn btn-primary" onclick="filterContacts('Colleague')">同事</button>
            <button type="button" class="btn btn-primary" onclick="filterContacts('Family')">家人</button>
            <button type="button" class="btn btn-primary" onclick="filterContacts('Friend')">朋友</button>
        </div>

        <div class="table container-fluid">
            <table>
                <thead>
                <tr>
                    <th></th>
                    <th>ID</th>
                    <th>姓名</th>
                    <th>电话</th>
                    <th>备注</th>
                </tr>
                </thead>
                <tbody id="contactList">
                <tr th:each="addressBook : ${addressBook}">
                    <th></th>
                    <th th:text="${addressBook.id}">ID</th>
                    <th th:text="${addressBook.name}">姓名</th>
                    <th th:text="${addressBook.phone}">电话</th>
                    <th th:text="${addressBook.label}">备注</th>
                </tr>
                </tbody>
            </table>
        </div><br>

        <div class="pagination">
            <a href="#" class="first-page">首页</a>
            <a href="#" class="prev-page">上一页</a>
            <span class="page-numbers"></span>
            <a href="#" class="next-page">下一页</a>
            <a href="#" class="last-page">尾页</a>
            <input type="text" class="jump-to-page" placeholder="请输入跳转页码">
            <button class="go-to-page">跳转</button>
        </div><br>

        <div class="btn-group">
            <button type="button" class="btn btn-primary" onclick="createContact()">新建联系人</button>
            <button type="button" class="btn btn-danger" onclick="deleteSelectedContacts()">删除选中联系人</button>
        </div>
    </form>

</div>

<script>

    var currentPage = 1;
    var totalPages = 0;
    var url="";
    $('#userWelcome').append("<p>"+"欢迎，"+localStorage.getItem('welcome')+"</p>");

    // 页面加载完成后初始化联系人列表
    $(document).ready(function() {
        url = '/doAddressBook/byPage';
        getAddressBook(1,10);
    });


    // 获取联系人数据
    function getAddressBook(pageNum,pageSize) {

        $.ajax({
            url: url,
            type: 'GET',
            data: {
                pageNum: pageNum,
                pageSize: pageSize
            },
            success: function (data) {
                // 用新数据更新表
                // 更新分页组件
                currentPage = data.pageNum;
                totalPages = data.pages;
                updatePagination();
                updateTableItems(data);
            },
            error: function (xhr, status, error) {
                console.log('Error: ' + error);
            }
        });
    }

    // 渲染联系人列表
    function updateTableItems(data) {
        var tableBody = $("#contactList");
        tableBody.empty();

        data.list.forEach((addressBook) =>{
            var row = $("<tr></tr>");
            row.append("<td><input type='checkbox' class='contact-checkbox' value='" + addressBook.id + "'></td>");
            row.append("<td>" + addressBook.id + "</td>");
            row.append("<td class='contact-list-item' onclick='viewContactDetails(" + addressBook.id + ")'>" + addressBook.name + "</td>");
            row.append("<td>" + addressBook.phoneNumber + "</td>");
            row.append("<td>" + addressBook.label + "</td>");
            tableBody.append(row);
        });
    }


    // 渲染分页控件
    function updatePagination() {
        var pageNumbers = '';
        for (var i = 1; i <= totalPages; i++) {
            if (i == currentPage) {
                pageNumbers += '<span class="current-page">' + i + ' </span>';
            } else {
                pageNumbers += '<a href="#" class="page-number">' + i + '</a>';
            }
        }
        $('.pagination .page-numbers').html(pageNumbers);
    }


    // 处理分页按钮单机事件
    $('.pagination .first-page').click(function (e) {
        e.preventDefault();
        getAddressBook(1, 10);
    });
    $('.pagination .prev-page').click(function (e) {
        e.preventDefault();
        if (currentPage > 1) {
            getAddressBook(currentPage - 1, 10);
        }
    });
    $('.pagination').on('click', '.page-number', function(e) {
        e.preventDefault();
        var pageNum = $(this).text();
        getAddressBook(pageNum, 10);
    });

    $('.pagination .next-page').click(function (e) {
        e.preventDefault();
        if (currentPage < totalPages) {
            getAddressBook(currentPage + 1, 10);
        }
    });
    $('.pagination .last-page').click(function (e) {
        e.preventDefault();
        getAddressBook(totalPages, 10);
    });
    // 处理跳转到页面的输入
    $('.pagination .go-to-page').click(function (e) {
        e.preventDefault();
        var pageNum = parseInt($('.pagination .jump-to-page').val());
        if (pageNum >= 1 && pageNum <= totalPages) {
            getAddressBook(pageNum, 10);
        }
    });

    // 模糊查询
    $("#searchButton").click(
        function () {
            var condition = $("#searchInput").val();
            url = '/doAddressBook/fuzzyQuery/' + condition;
            getAddressBook(1,10);
        }
    )

    // 根据标签过滤联系人
    function filterContacts(label) {
        // 进行分类筛选的函数
        if (label == "all"){
            url = '/doAddressBook/byPage';
        }else {
            url = '/doAddressBook/label/' + label;
        }
        getAddressBook(1,10);
    }

    // 查看联系人详情
    function viewContactDetails(id) {
        // 根据id跳转至联系人详情页面
        window.location.href = "contactDetails?id=" + id;
        console.log("查看联系人详情，ID：" + id);
    }

    // 创建联系人
    function createContact() {
        // 跳转至添加联系人页面
        window.location.href = "newContact";
        // console.log("跳转至添加联系人页面");
    }

    function deleteSelectedContacts() {
        var selectedContacts = [];
        $(".contact-checkbox:checked").each(function() {
            var contactId = parseInt($(this).val());
            selectedContacts.push(contactId);
        });

        // 在此处执行删除选中联系人的逻辑，可以通过AJAX请求向服务器发送删除请求
        $.ajax({
            url: '/doAddressBook/delete',  // 控制器的URL路径
            type: 'DELETE',  // 使用 DELETE 方法发送请求
            data: JSON.stringify(selectedContacts),  // 将选中联系人的ID作为请求的数据发送给服务器
            contentType: 'application/json',  // 声明请求体的数据类型为JSON
            success: function() {
                // 重新渲染联系人列表
                getAddressBook(1, 10);
            },
            error: function(xhr, status, error) {
                console.log('Error: ' + error);
            }
        });
    }

</script>
</body>
</html>